using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Chan_cli.Modules
{
    class FilesModule : Module
    {

        // Variable
        string RootDir;

        // Constructor
        public FilesModule(string Dir)
        {

            RootDir = Dir;

        }

        // Does file exist? Hm. That is the question.
        public override bool PathExist(string[] Path)
        {

            // Array stuffs >.>
            string sPath = ArrayToString(Path);
            Console.WriteLine(RootDir + sPath + ": " + File.Exists(RootDir + sPath).ToString());
            // Does it exist
            return File.Exists(RootDir + sPath);

        }

        // Request file..
        public override byte[] Request(string[] Path)
        {

            // Array stuffs >.>
            string sPath = ArrayToString(Path);

            // Open file!
            FileStream S = File.Open(RootDir + sPath, FileMode.Open);
            
            // Read!
            byte[] buffer = new byte[S.Length];
            S.Read(buffer, 0, (int)S.Length);

            // Close
            S.Close();
            S = null;

            // Return.
            return buffer;

        }
        
        // Request File .. With data!
        public override byte[] RequestData(string[] Path, POSTData[] Data)
        {
        
        	// We don't need to parse data for this module, so just serve regularly
        	return Request(Path);
        
        }

        // Private function to make life easier!
        private string ArrayToString(string[] Arr)
        {

            // From string[] to string!
            string Str = string.Empty;
            foreach (string s in Arr)
                Str += "/" + s;

            return "/" + Str.Substring(7, Str.Length - 7); // Get rid of /files at start!

        }

    }
}
